import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Drawer,
  Descriptions,
  Avatar,
  Tooltip,
  Row,
  Col,
  Statistic,
  Tabs,
  Timeline,
  Switch,
  Badge,
  Progress,
  Divider,
  Upload,
  Steps
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  CopyOutlined,
  DownloadOutlined,
  UploadOutlined,
  SettingOutlined,
  UserOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  BranchesOutlined,
  NodeIndexOutlined,
  ReloadOutlined,
  FileTextOutlined,
  ApiOutlined,
  CloudUploadOutlined,
  DeploymentUnitOutlined,
  HistoryOutlined
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { 
  FlowableWorkflowService, 
  type ProcessDefinition, 
  type ProcessInstance, 
  type Deployment,
  type Task,
  type WorkflowTemplate 
} from '../services/workflowService';
import ProcessDesigner from '../components/ProcessDesigner';
import ProcessTemplates from '../components/ProcessTemplates';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;
const { Step } = Steps;
const { Dragger } = Upload;

const workflowService = new FlowableWorkflowService();

export default function WorkflowManagement() {
  // 流程定义相关状态
  const [processDefinitions, setProcessDefinitions] = useState<ProcessDefinition[]>([]);
  const [deployments, setDeployments] = useState<Deployment[]>([]);
  const [processInstances, setProcessInstances] = useState<ProcessInstance[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [templates, setTemplates] = useState<WorkflowTemplate[]>([]);
  
  // UI状态
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isDetailDrawerVisible, setIsDetailDrawerVisible] = useState(false);
  const [isDesignerVisible, setIsDesignerVisible] = useState(false);
  const [templatesVisible, setTemplatesVisible] = useState(false);
  const [isDeployModalVisible, setIsDeployModalVisible] = useState(false);
  
  // 选中的数据
  const [selectedProcessDefinition, setSelectedProcessDefinition] = useState<ProcessDefinition | null>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<WorkflowTemplate | null>(null);
  const [editingProcessDefinition, setEditingProcessDefinition] = useState<ProcessDefinition | null>(null);
  
  // 当前活动标签页
  const [activeTab, setActiveTab] = useState('definitions');
  
  // 表单和筛选
  const [form] = Form.useForm();
  const [deployForm] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [categoryFilter, setCategoryFilter] = useState<string>('');
  
  // 统计数据
  const [statistics, setStatistics] = useState({
    totalDefinitions: 0,
    activeDefinitions: 0,
    suspendedDefinitions: 0,
    totalInstances: 0,
    runningInstances: 0,
    completedInstances: 0,
    totalTasks: 0,
    pendingTasks: 0
  });

  useEffect(() => {
    loadData();
  }, [activeTab]);

  const loadData = async () => {
    setLoading(true);
    try {
      switch (activeTab) {
        case 'definitions':
          await loadProcessDefinitions();
          break;
        case 'deployments':
          await loadDeployments();
          break;
        case 'instances':
          await loadProcessInstances();
          break;
        case 'tasks':
          await loadTasks();
          break;
        case 'templates':
          await loadTemplates();
          break;
      }
      await loadStatistics();
    } catch (error: any) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const loadProcessDefinitions = async () => {
    try {
      const response = await workflowService.getProcessDefinitions({
        page: 0,
        size: 100,
        latest: true
      });
      setProcessDefinitions(response.data || []);
    } catch (error: any) {
      console.error('加载流程定义失败:', error);
      message.error('加载流程定义失败');
    }
  };

  const loadDeployments = async () => {
    try {
      const response = await workflowService.getDeployments({
        page: 0,
        size: 100
      });
      setDeployments(response.data || []);
    } catch (error: any) {
      console.error('加载部署列表失败:', error);
      message.error('加载部署列表失败');
    }
  };

  const loadProcessInstances = async () => {
    try {
      const response = await workflowService.getProcessInstances({
        page: 0,
        size: 100
      });
      setProcessInstances(response.data || []);
    } catch (error: any) {
      console.error('加载流程实例失败:', error);
      message.error('加载流程实例失败');
    }
  };

  const loadTasks = async () => {
    try {
      const response = await workflowService.getTasks({
        page: 0,
        size: 100
      });
      setTasks(response.data || []);
    } catch (error: any) {
      console.error('加载任务列表失败:', error);
      message.error('加载任务列表失败');
    }
  };

  const loadTemplates = async () => {
    try {
      const response = await workflowService.getWorkflowTemplates();
      setTemplates(response || []);
    } catch (error: any) {
      console.error('加载模板列表失败:', error);
      message.error('加载模板列表失败');
    }
  };

  const loadStatistics = async () => {
    try {
      const stats = await workflowService.getStatistics();
      setStatistics(stats);
    } catch (error: any) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 创建新的流程定义（通过BPMN设计器）
  const handleCreateProcess = () => {
    setEditingProcessDefinition(null);
    setIsDesignerVisible(true);
  };

  // 从模板创建流程定义
  const handleCreateFromTemplate = async (template: WorkflowTemplate) => {
    try {
      setSelectedTemplate(template);
      setEditingProcessDefinition(null);
      setIsDesignerVisible(true);
      setTemplatesVisible(false);
      message.success('已加载模板，请在设计器中完善流程定义');
    } catch (error: any) {
      console.error('从模板创建失败:', error);
      message.error('从模板创建失败: ' + (error.message || '未知错误'));
    }
  };

  // 部署流程定义
  const handleDeploy = (processDefinition?: ProcessDefinition) => {
    if (processDefinition) {
      setSelectedProcessDefinition(processDefinition);
    }
    setIsDeployModalVisible(true);
  };

  // 执行部署
  const handleDeploySubmit = async () => {
    try {
      const values = await deployForm.validateFields();
      
      if (selectedProcessDefinition?.resourceName) {
        // 部署现有流程定义
        await workflowService.deployProcessDefinition(
          selectedProcessDefinition.resourceName,
          values.deploymentName,
          values.category
        );
      }
      
      message.success('部署成功');
      setIsDeployModalVisible(false);
      deployForm.resetFields();
      await loadData();
    } catch (error: any) {
      console.error('部署失败:', error);
      message.error('部署失败: ' + (error.message || '未知错误'));
    }
  };

  // 启动流程实例
  const handleStartInstance = async (processDefinitionKey: string) => {
    try {
      const businessKey = `BK_${Date.now()}`;
      await workflowService.startProcessInstance(processDefinitionKey, {
        businessKey,
        variables: {}
      });
      message.success('流程实例启动成功');
      if (activeTab === 'instances') {
        await loadProcessInstances();
      }
    } catch (error: any) {
      console.error('启动流程实例失败:', error);
      message.error('启动流程实例失败: ' + (error.message || '未知错误'));
    }
  };

  // 暂停/激活流程定义
  const handleToggleProcessDefinition = async (id: string, suspended: boolean) => {
    try {
      if (suspended) {
        await workflowService.activateProcessDefinition(id);
        message.success('流程定义已激活');
      } else {
        await workflowService.suspendProcessDefinition(id);
        message.success('流程定义已暂停');
      }
      await loadProcessDefinitions();
    } catch (error: any) {
      console.error('操作失败:', error);
      message.error('操作失败: ' + (error.message || '未知错误'));
    }
  };

  // 删除部署
  const handleDeleteDeployment = async (deploymentId: string) => {
    try {
      await workflowService.deleteDeployment(deploymentId, true);
      message.success('部署删除成功');
      await loadData();
    } catch (error: any) {
      console.error('删除部署失败:', error);
      message.error('删除部署失败: ' + (error.message || '未知错误'));
    }
  };

  // 查看详情
  const handleViewDetails = (record: any) => {
    setSelectedProcessDefinition(record);
    setIsDetailDrawerVisible(true);
  };

  // 编辑流程定义
  const handleEdit = (record: ProcessDefinition) => {
    setEditingProcessDefinition(record);
    setIsDesignerVisible(true);
  };

  // 文件上传处理
  const handleFileUpload = async (file: File) => {
    try {
      const deploymentName = `Deployment_${Date.now()}`;
      await workflowService.deployProcessDefinition(file, deploymentName);
      message.success('BPMN文件上传部署成功');
      await loadData();
      return false; // 阻止默认上传行为
    } catch (error: any) {
      console.error('上传失败:', error);
      message.error('上传失败: ' + (error.message || '未知错误'));
      return false;
    }
  };

  // 获取状态颜色
  const getStatusColor = (suspended: boolean) => {
    return suspended ? 'orange' : 'green';
  };

  // 获取状态文本
  const getStatusText = (suspended: boolean) => {
    return suspended ? '已暂停' : '活跃';
  };

  // 筛选数据
  const filteredProcessDefinitions = processDefinitions.filter(def => {
    const matchesSearch = !searchText || 
      def.name?.toLowerCase().includes(searchText.toLowerCase()) ||
      def.key?.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesStatus = !statusFilter || 
      (statusFilter === 'active' && !def.suspended) ||
      (statusFilter === 'suspended' && def.suspended);
    
    const matchesCategory = !categoryFilter || def.category === categoryFilter;
    
    return matchesSearch && matchesStatus && matchesCategory;
  });

  // 流程定义表格列
  const processDefinitionColumns: ColumnsType<ProcessDefinition> = [
    {
      title: '流程名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text, record) => (
        <div>
          <div className="font-medium">{text || record.key}</div>
          <div className="text-xs text-gray-500">Key: {record.key}</div>
        </div>
      )
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 80,
      render: (version) => <Tag color="blue">v{version}</Tag>
    },
    {
      title: '状态',
      dataIndex: 'suspended',
      key: 'suspended',
      width: 100,
      render: (suspended) => (
        <Tag color={getStatusColor(suspended)}>
          {getStatusText(suspended)}
        </Tag>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120
    },
    {
      title: '部署时间',
      dataIndex: 'deploymentTime',
      key: 'deploymentTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="编辑流程">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="启动实例">
            <Button 
              type="text" 
              icon={<PlayCircleOutlined />} 
              onClick={() => handleStartInstance(record.key!)}
            />
          </Tooltip>
          <Tooltip title={record.suspended ? '激活' : '暂停'}>
            <Button 
              type="text" 
              icon={record.suspended ? <PlayCircleOutlined /> : <PauseCircleOutlined />} 
              onClick={() => handleToggleProcessDefinition(record.id!, record.suspended!)}
            />
          </Tooltip>
          <Tooltip title="部署">
            <Button 
              type="text" 
              icon={<DeploymentUnitOutlined />} 
              onClick={() => handleDeploy(record)}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  // 部署表格列
  const deploymentColumns: ColumnsType<Deployment> = [
    {
      title: '部署名称',
      dataIndex: 'name',
      key: 'name',
      width: 200
    },
    {
      title: '部署ID',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      render: (id) => <code className="text-xs">{id}</code>
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120
    },
    {
      title: '部署时间',
      dataIndex: 'deploymentTime',
      key: 'deploymentTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '租户ID',
      dataIndex: 'tenantId',
      key: 'tenantId',
      width: 120,
      render: (tenantId) => tenantId || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个部署吗？"
            description="删除部署将同时删除相关的流程定义和实例"
            onConfirm={() => handleDeleteDeployment(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除部署">
              <Button 
                type="text" 
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 流程实例表格列
  const processInstanceColumns: ColumnsType<ProcessInstance> = [
    {
      title: '实例ID',
      dataIndex: 'id',
      key: 'id',
      width: 200,
      render: (id) => <code className="text-xs">{id}</code>
    },
    {
      title: '流程定义',
      dataIndex: 'processDefinitionName',
      key: 'processDefinitionName',
      width: 200,
      render: (name, record) => (
        <div>
          <div className="font-medium">{name || record.processDefinitionKey}</div>
          <div className="text-xs text-gray-500">Key: {record.processDefinitionKey}</div>
        </div>
      )
    },
    {
      title: '业务键',
      dataIndex: 'businessKey',
      key: 'businessKey',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'ended',
      key: 'ended',
      width: 100,
      render: (ended, record) => (
        <Tag color={ended ? 'default' : record.suspended ? 'orange' : 'green'}>
          {ended ? '已结束' : record.suspended ? '已暂停' : '运行中'}
        </Tag>
      )
    },
    {
      title: '启动时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          {!record.ended && (
            <Tooltip title={record.suspended ? '激活' : '暂停'}>
              <Button 
                type="text" 
                icon={record.suspended ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
              />
            </Tooltip>
          )}
        </Space>
      )
    }
  ];

  // 任务表格列
  const taskColumns: ColumnsType<Task> = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      width: 200
    },
    {
      title: '执行人',
      dataIndex: 'assignee',
      key: 'assignee',
      width: 120,
      render: (assignee) => assignee || '未分配'
    },
    {
      title: '流程实例',
      dataIndex: 'processInstanceId',
      key: 'processInstanceId',
      width: 200,
      render: (id) => <code className="text-xs">{id}</code>
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '到期时间',
      dataIndex: 'dueDate',
      key: 'dueDate',
      width: 150,
      render: (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 100,
      render: (priority) => (
        <Tag color={priority >= 75 ? 'red' : priority >= 50 ? 'orange' : 'blue'}>
          {priority || 50}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              onClick={() => handleViewDetails(record)}
            />
          </Tooltip>
          <Tooltip title="完成任务">
            <Button 
              type="text" 
              icon={<CheckCircleOutlined />}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="流程定义"
              value={statistics.totalDefinitions}
              prefix={<BranchesOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="活跃定义"
              value={statistics.activeDefinitions}
              prefix={<PlayCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="流程实例"
              value={statistics.totalInstances}
              prefix={<NodeIndexOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="运行实例"
              value={statistics.runningInstances}
              prefix={<SyncOutlined spin />}
              valueStyle={{ color: '#13c2c2' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="待办任务"
              value={statistics.pendingTasks}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={4}>
          <Card>
            <Statistic
              title="总任务数"
              value={statistics.totalTasks}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#ff7a45' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容 */}
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          {/* 流程定义管理 */}
          <TabPane tab="流程定义" key="definitions">
            <div className="mb-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold">流程定义管理</h3>
                <Space>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />} 
                    onClick={handleCreateProcess}
                  >
                    新建流程
                  </Button>
                  <Button 
                    icon={<FileTextOutlined />} 
                    onClick={() => setTemplatesVisible(true)}
                  >
                    流程模板
                  </Button>
                  <Button 
                    icon={<DeploymentUnitOutlined />} 
                    onClick={() => handleDeploy()}
                  >
                    部署流程
                  </Button>
                  <Upload
                    accept=".bpmn,.xml"
                    showUploadList={false}
                    beforeUpload={handleFileUpload}
                  >
                    <Button icon={<UploadOutlined />}>
                      上传BPMN
                    </Button>
                  </Upload>
                  <Button icon={<ReloadOutlined />} onClick={loadData}>
                    刷新
                  </Button>
                </Space>
              </div>
              
              {/* 筛选器 */}
              <Row gutter={[16, 16]} className="mb-4">
                <Col xs={24} sm={12} md={8}>
                  <Input.Search
                    placeholder="搜索流程名称或Key"
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    allowClear
                  />
                </Col>
                <Col xs={24} sm={12} md={4}>
                  <Select
                    placeholder="状态筛选"
                    value={statusFilter}
                    onChange={setStatusFilter}
                    allowClear
                    className="w-full"
                  >
                    <Option value="active">活跃</Option>
                    <Option value="suspended">已暂停</Option>
                  </Select>
                </Col>
                <Col xs={24} sm={12} md={4}>
                  <Select
                    placeholder="分类筛选"
                    value={categoryFilter}
                    onChange={setCategoryFilter}
                    allowClear
                    className="w-full"
                  >
                    <Option value="用户管理">用户管理</Option>
                    <Option value="数据管理">数据管理</Option>
                    <Option value="权限管理">权限管理</Option>
                    <Option value="系统管理">系统管理</Option>
                  </Select>
                </Col>
              </Row>
            </div>

            <Table
              columns={processDefinitionColumns}
              dataSource={filteredProcessDefinitions}
              rowKey="id"
              loading={loading}
              pagination={{
                total: filteredProcessDefinitions.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
              rowSelection={{
                selectedRowKeys,
                onChange: setSelectedRowKeys
              }}
            />
          </TabPane>

          {/* 部署管理 */}
          <TabPane tab="部署管理" key="deployments">
            <div className="mb-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold">部署管理</h3>
                <Space>
                  <Button 
                    icon={<DeploymentUnitOutlined />} 
                    onClick={() => handleDeploy()}
                  >
                    新建部署
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={loadData}>
                    刷新
                  </Button>
                </Space>
              </div>
            </div>

            <Table
              columns={deploymentColumns}
              dataSource={deployments}
              rowKey="id"
              loading={loading}
              pagination={{
                total: deployments.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          </TabPane>

          {/* 流程实例 */}
          <TabPane tab="流程实例" key="instances">
            <div className="mb-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold">流程实例管理</h3>
                <Space>
                  <Button icon={<ReloadOutlined />} onClick={loadData}>
                    刷新
                  </Button>
                </Space>
              </div>
            </div>

            <Table
              columns={processInstanceColumns}
              dataSource={processInstances}
              rowKey="id"
              loading={loading}
              pagination={{
                total: processInstances.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          </TabPane>

          {/* 任务管理 */}
          <TabPane tab="任务管理" key="tasks">
            <div className="mb-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold">任务管理</h3>
                <Space>
                  <Button icon={<ReloadOutlined />} onClick={loadData}>
                    刷新
                  </Button>
                </Space>
              </div>
            </div>

            <Table
              columns={taskColumns}
              dataSource={tasks}
              rowKey="id"
              loading={loading}
              pagination={{
                total: tasks.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`
              }}
            />
          </TabPane>

          {/* 流程模板 */}
          <TabPane tab="流程模板" key="templates">
            <div className="mb-4">
              <div className="flex justify-between items-center mb-4">
                <h3 className="text-lg font-semibold">流程模板库</h3>
                <Space>
                  <Button icon={<ReloadOutlined />} onClick={loadData}>
                    刷新
                  </Button>
                </Space>
              </div>
            </div>

            <ProcessTemplates
              templates={templates}
              onCreateFromTemplate={handleCreateFromTemplate}
              loading={loading}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 流程设计器模态框 */}
      <Modal
        title={editingProcessDefinition ? '编辑流程定义' : '新建流程定义'}
        open={isDesignerVisible}
        onCancel={() => {
          setIsDesignerVisible(false);
          setEditingProcessDefinition(null);
          setSelectedTemplate(null);
        }}
        width="90%"
        style={{ top: 20 }}
        footer={null}
        destroyOnClose
      >
        <ProcessDesigner
          processId={editingProcessDefinition?.id}
          templateXml={selectedTemplate?.bpmnXml}
          onSave={async (bpmnXml: string, processName: string) => {
            try {
              // 仅保存BPMN，不部署
              // 这里可以保存为草稿或模板
              message.success('流程定义保存成功');
              setIsDesignerVisible(false);
              await loadData();
            } catch (error: any) {
              console.error('保存失败:', error);
              message.error('保存失败: ' + (error.message || '未知错误'));
            }
          }}
          onDeploy={async (bpmnXml: string, processName: string) => {
            try {
              // 部署BPMN到Flowable引擎
              const deploymentName = `${processName}_${Date.now()}`;
              await workflowService.deployProcessDefinition(
                new Blob([bpmnXml], { type: 'application/xml' }) as any,
                deploymentName
              );
              message.success('流程定义部署成功');
              setIsDesignerVisible(false);
              await loadData();
            } catch (error: any) {
              console.error('部署失败:', error);
              message.error('部署失败: ' + (error.message || '未知错误'));
            }
          }}
        />
      </Modal>

      {/* 部署模态框 */}
      <Modal
        title="部署流程定义"
        open={isDeployModalVisible}
        onOk={handleDeploySubmit}
        onCancel={() => {
          setIsDeployModalVisible(false);
          deployForm.resetFields();
        }}
        okText="部署"
        cancelText="取消"
      >
        <Form
          form={deployForm}
          layout="vertical"
          initialValues={{
            deploymentName: `Deployment_${Date.now()}`,
            category: '默认分类'
          }}
        >
          <Form.Item
            label="部署名称"
            name="deploymentName"
            rules={[{ required: true, message: '请输入部署名称' }]}
          >
            <Input placeholder="请输入部署名称" />
          </Form.Item>
          
          <Form.Item
            label="分类"
            name="category"
          >
            <Select placeholder="请选择分类">
              <Option value="用户管理">用户管理</Option>
              <Option value="数据管理">数据管理</Option>
              <Option value="权限管理">权限管理</Option>
              <Option value="系统管理">系统管理</Option>
            </Select>
          </Form.Item>

          {!selectedProcessDefinition && (
            <Form.Item label="BPMN文件">
              <Dragger
                accept=".bpmn,.xml"
                beforeUpload={() => false}
                onChange={(info) => {
                  if (info.file.status === 'done') {
                    message.success('文件选择成功');
                  }
                }}
              >
                <p className="ant-upload-drag-icon">
                  <CloudUploadOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽BPMN文件到此区域上传</p>
                <p className="ant-upload-hint">支持.bpmn和.xml格式文件</p>
              </Dragger>
            </Form.Item>
          )}
        </Form>
      </Modal>

      {/* 流程模板选择器 */}
      <Modal
        title="选择流程模板"
        open={templatesVisible}
        onCancel={() => setTemplatesVisible(false)}
        width="80%"
        footer={null}
      >
        <ProcessTemplates
          onCreateFromTemplate={handleCreateFromTemplate}
        />
      </Modal>

      {/* 详情抽屉 */}
      <Drawer
        title="详细信息"
        placement="right"
        onClose={() => setIsDetailDrawerVisible(false)}
        open={isDetailDrawerVisible}
        width={600}
      >
        {selectedProcessDefinition && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="ID">
              <code>{selectedProcessDefinition.id}</code>
            </Descriptions.Item>
            <Descriptions.Item label="名称">
              {selectedProcessDefinition.name || selectedProcessDefinition.key}
            </Descriptions.Item>
            <Descriptions.Item label="Key">
              <code>{selectedProcessDefinition.key}</code>
            </Descriptions.Item>
            <Descriptions.Item label="版本">
              <Tag color="blue">v{selectedProcessDefinition.version}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getStatusColor(selectedProcessDefinition.suspended!)}>
                {getStatusText(selectedProcessDefinition.suspended!)}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="分类">
              {selectedProcessDefinition.category || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="部署ID">
              <code>{selectedProcessDefinition.deploymentId}</code>
            </Descriptions.Item>
            <Descriptions.Item label="资源名称">
              {selectedProcessDefinition.resourceName}
            </Descriptions.Item>
            <Descriptions.Item label="部署时间">
              {selectedProcessDefinition.deploymentTime ? 
                dayjs(selectedProcessDefinition.deploymentTime).format('YYYY-MM-DD HH:mm:ss') : '-'
              }
            </Descriptions.Item>
            <Descriptions.Item label="租户ID">
              {selectedProcessDefinition.tenantId || '-'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
}